package com.dhl.cloud.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.dhl.cloud.common.Constants;
import com.dhl.cloud.common.http.HttpResult;
import com.dhl.cloud.common.vdo.UploadBean;
import com.dhl.cloud.course.entity.LessionTransaudio;
import com.dhl.cloud.course.service.LessionTransaudioService;
import com.dhl.cloud.course.service.LessionTranscriptmutService;

/**
 * 上传接口
 *
 */
@RestController
@RequestMapping(value = "/user")
public class UploadController extends BaseController {

    @Value("${fileUpload.rootSavePath}")
    private String rootSavePath;
    @Autowired
    private LessionTransaudioService lessionTransaudioService;
    @Autowired
    private LessionTranscriptmutService lessionTranscriptmutService;
    
    @PostMapping(value = "/uploadtransfile")
    public HttpResult uploadtransfile(@RequestParam("file") MultipartFile file, HttpServletRequest request,
                                    @RequestParam(value = "targetpath", required = false) String path,
                                    @RequestParam(value = "courseid", required = true) String courseid,
                                    @RequestParam(value = "lessionid", required = true) String lessionid,
                                    @RequestParam(value = "lessionnum", required = true) String lessionnum,                                    
                                    @RequestParam(value = "targetname", required = false) String name) {
        if (file.isEmpty()) {
            return HttpResult.error(Constants.ERROR_MSG_15);
        }
        // 文件名
        String filename = file.getOriginalFilename();
        
        // 文件后缀
        String suffixName = filename.substring(filename.lastIndexOf("."));
        //这儿有点小问题，原则上上传后我需要改名的，为了排除重名，定义了targetname，如果有这个值就以targetname存入       
        if (StringUtils.isNotEmpty(name))
        {
        	filename = name + suffixName;
        }
        else
        {
        	filename = UUID.randomUUID() + suffixName;
        }
        
        // 存放文件的路径
//        String path = request.getParameter("targetpath");
        if (StringUtils.isEmpty(path))
        {
        	path = "";
        }
        String fp = rootSavePath + path + "/" + filename;
        File dest = new File(fp);
        if (!dest.getParentFile().exists()) {
            //父目录不存在就创建一个
            dest.getParentFile().mkdirs();
        }
        //保存文件
        try {
            file.transferTo(dest);
            String fileSize = FormetFileSize(file.getSize());
            
            //audio文件保存到数据库
            LessionTransaudio lessionfile = new LessionTransaudio();
            lessionfile.setCourseid(Integer.parseInt(courseid));
            lessionfile.setLessionid(Integer.parseInt(lessionid));
            lessionfile.setFilename(filename);
            lessionfile.setFilepath("/Path"+ path + "/" + filename);
            lessionfile.setLessionnum(lessionnum);
            lessionfile.setFilesize(fileSize);
            lessionTransaudioService.insert(lessionfile);
            //合并lessiontranscript的翻译结果到lessiontranscriptmut里面
            lessionTranscriptmutService.mergeTranscript(lessionnum,rootSavePath);
            
            UploadBean ub = new UploadBean();
            ub.setFilepath("/Path"+ path + "/" + filename);
			
			ub.setFilesize(fileSize);
            return HttpResult.success("",ub);
        } catch (IOException e) {
            e.printStackTrace();
            return HttpResult.error(Constants.ERROR_MSG_16);
        }
    }
    
    @PostMapping(value = "/upload")
    public HttpResult fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request,
                                    @RequestParam(value = "targetpath", required = false) String path,@RequestParam(value = "targetname", required = false) String name) {
        if (file.isEmpty()) {
            return HttpResult.error(Constants.ERROR_MSG_15);
        }
        // 文件名
        String filename = file.getOriginalFilename();
        
        // 文件后缀
        String suffixName = filename.substring(filename.lastIndexOf("."));
        //这儿有点小问题，原则上上传后我需要改名的，为了排除重名，定义了targetname，如果有这个值就以targetname存入
        if (".document".equals(suffixName))
        {
        	suffixName = ".docx";
        }
        else if (".presentation".equals(suffixName))
        {
        	suffixName = ".pptx";
        }
        if (StringUtils.isNotEmpty(name))
        {
        	filename = name + suffixName;
        }
        else
        {
        	filename = UUID.randomUUID() + suffixName;
        }
        
        // 存放文件的路径
//        String path = request.getParameter("targetpath");
        if (StringUtils.isEmpty(path))
        {
        	path = "";
        }
        String fp = rootSavePath + path + "/" + filename;
        File dest = new File(fp);
        if (!dest.getParentFile().exists()) {
            //父目录不存在就创建一个
            dest.getParentFile().mkdirs();
        }
        //保存文件
        try {
            file.transferTo(dest);
            UploadBean ub = new UploadBean();
            ub.setFilepath("/Path"+ path + "/" + filename);
			String fileSize = FormetFileSize(file.getSize());
			ub.setFilesize(fileSize);
            return HttpResult.success("",ub);
        } catch (IOException e) {
            e.printStackTrace();
            return HttpResult.error(Constants.ERROR_MSG_16);
        }
    }

	@GetMapping("/download")
	public HttpServletResponse download(String filepath,HttpServletRequest request,HttpServletResponse response) {
//		try {
////			String filepath = bean.getFilepath();
//			filepath = rootSavePath + filepath.replace("/Path", "");
//			File file = new File(filepath);
////			OutputStream out = new FileOutputStream(file);
//			// 以流的形式下载文件。
//			InputStream fis = new BufferedInputStream(new FileInputStream(file));
//			/*byte[] buffer = new byte[fis.available()];
//			fis.read(buffer);
//			fis.close();*/
//			// 清空response
//			response.reset();
//            
//			String referer = request.getHeader("origin");
//			if (referer != null) {
//			  URL url = new URL(referer);
//			  String origin = url.getProtocol() + "://" + url.getHost();
//			  if(url.getPort()!=-1){
//				  origin+=":"+url.getPort();
//			  }
//			  response.addHeader("Access-Control-Allow-Origin", origin);
//			  response.addHeader("Access-Control-Allow-Credentials", "true");
//			} else {
//			  response.addHeader("Access-Control-Allow-Origin", "*");
//			}
//		    response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
//		    response.addHeader("Access-Control-Allow-Headers", "Content-Type");
//		
//			// 设置response的Header
////			filename = processFileName(request, filename);
//			response.setCharacterEncoding("UTF-8");
//	        response.setContentType("application/vnd.ms-excel");
//			response.addHeader("Content-Disposition", "attachment;filename="
//					+ new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
//			response.addHeader("Content-Length", "" + file.length());
//			response.setContentType("application/octet-stream");
//			OutputStream toClient = new BufferedOutputStream(
//					response.getOutputStream());
//			// //加上UTF-8文件的标识字符
//			// toClient.write(new byte []{(byte) 0xEF ,(byte) 0xBB ,(byte)
//			// 0xBF});
//			byte[] buffer = new byte[1024 * 1024 * 10];// 5MB
//			int len = 0;
//			while ((len = fis.read(buffer)) != -1) {
//				toClient.write(buffer, 0, len);
//			}
//			fis.close();
//			//toClient.write(buffer);
//			toClient.flush();
//			toClient.close();
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		
		
        InputStream in = null;
        OutputStream toClient = null;
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("charset", "utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Transfer-Encoding", "binary");
        try {
        	
        	filepath = rootSavePath + filepath.replace("/Path", "");
			File file = new File(filepath);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(file.getName().getBytes("UTF-8"),"ISO8859-1") + "\"");
            in = new FileInputStream(file);
            //3.通过response获取ServletOutputStream对象(out)
            toClient = new BufferedOutputStream(
                    response.getOutputStream());
            int b = 0;
            byte[] buffer = new byte[1024 * 1024 * 20];
            while (b != -1){
                b = in.read(buffer);
                if(b != -1){
                    toClient.write(buffer,0,b);//4.写到输出流(out)中
                }

            }
            toClient.flush();
        } catch (Exception e) {
        }finally{
            try {
                if (in != null) {
                    in.close();
                }
                if (toClient != null){
                    toClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
	}

	private String FormetFileSize(long fileS)
	{
		DecimalFormat df = new DecimalFormat("#.0");
		String fileSizeString = "";
		if(fileS < 1024L)
			fileSizeString = (new StringBuilder()).append(df.format(fileS)).append("B").toString();
		else
		if(fileS < 0x100000L)
			fileSizeString = (new StringBuilder()).append(df.format((double)fileS / 1024D)).append("K").toString();
		else
		if(fileS < 0x40000000L)
			fileSizeString = (new StringBuilder()).append(df.format((double)fileS / 1048576D)).append("M").toString();
		else
			fileSizeString = (new StringBuilder()).append(df.format((double)fileS / 1073741824D)).append("G").toString();
		return fileSizeString;
	}


}
